package com.nuonuo.jingwei.es.config;

import com.nuonuo.jingwei.es.client.JingweiEsClientFactory;
import com.nuonuo.jingwei.es.client.base.exception.JingweiEsClientException;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.boot.env.OriginTrackedMapPropertySource;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.core.env.ConfigurableEnvironment;
import org.springframework.core.env.MutablePropertySources;
import org.springframework.core.env.PropertySource;

import java.io.IOException;
import java.util.Map;
import java.util.Properties;

/**
 * @author duan
 * @version 1.0
 * @date 2023/1/19 13:49
 */
@Configuration
public class JingweiEsConfig {

    private static final Logger logger = LoggerFactory.getLogger(JingweiEsConfig.class);

    @Autowired
    private ConfigurableEnvironment environment;

    @Value("${es2.cluster.id}")
    private String es2ClusterId;
    @Value("${es6.cluster.id}")
    private String es6ClusterId;
    @Value("${es7.cluster.id}")
    private String es7ClusterId;


    @Bean(name = "esClientFactory")
    public void StartJingweiEsClientFactory() {
        Properties properties = getProperties();
        try {
            JingweiEsClientFactory.start(properties);
        } catch (IOException | JingweiEsClientException e) {
            logger.error(e.getMessage(), e);
        }
    }

    private Properties getProperties() {
        Properties properties = new Properties();
        MutablePropertySources mutablePropertySources = environment.getPropertySources();
        for (PropertySource<?> propertySource : mutablePropertySources) {
            if (propertySource instanceof OriginTrackedMapPropertySource) {
                OriginTrackedMapPropertySource om = (OriginTrackedMapPropertySource) propertySource;
                Map<String, Object> source = om.getSource();
                for (Map.Entry<String, Object> entry : source.entrySet()) {
                    if (properties.getProperty(entry.getKey()) == null && entry.getValue() != null) {
                        properties.setProperty(entry.getKey(), entry.getValue().toString());
                    }
                }
            }
        }
        return properties;
    }
}
